package com.yjd.comm.user.interceptor;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.enums.ClientChannelEnum;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.user.util.LoginReturnUrlUtil;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.ServletUtil.UrlTypeEnum;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.util.TxtFileCacheUtil;
import com.yjd.comm.vo.CachedKeys;
import com.yjd.comm.vo.Constant.ResultEnum;

/**
 * <b>description</b>：登陆拦截器 <br>
 * <b>time</b>：2014-11-15下午12:39:48 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = Logger.getLogger(LoginInterceptor.class);
	private static String NO_LOGIN_URL_FILE = "nologinurl.txt";

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		request.setAttribute(ServletUtil.returnUrl,
				LoginReturnUrlUtil.getReturnUrl(request));
		// UserModel user = this.getUser(request, response); // 用户信息
		UserModel user = UserUtil.getUserModel(request, response, ClientChannelEnum.PIC); // 用户信息
		request.setAttribute(CachedKeys.LOGIN_USER, user);
		// 判断有没有在拦截排除列表中
		if (!urlIsNeedValidate(ServletUtil
				.getRquestUriNotContainContextPath(request))) {
			return super.preHandle(request, response, handler);
		}
		// 如果没有登录或者登录超时，记录当前访问地址，页面跳转到登录页面
		String loginUrl = ServletUtil.getUrl1("/login", UrlTypeEnum.USER_HTTPS,
				null, null);
		String referer = request.getHeader("Referer");
		String ajaxLoginUrl = loginUrl + (StringUtil.isNotEmpty(referer) ? "?returnUrl=" + URLEncoder.encode(request.getHeader("Referer"), "UTF-8") : "");
		String requestUrl = ServletUtil.getRequestUrlAndParam(request);
		if (user == null) {
			String returnUrl = null;
			if (!requestUrl.startsWith(loginUrl)) {
				returnUrl = requestUrl;
				loginUrl += "?returnUrl=" + URLEncoder.encode(returnUrl,"UTF-8");
			}
			if (ServletUtil.isAjaxRequest(request)) {
				FrameUtil.throwBaseException4(ResultEnum.NOLOGIN, null, ajaxLoginUrl,
						"请先登录");
			} else {
				response.sendRedirect(loginUrl);
			}
			return false;
		}

		return super.preHandle(request, response, handler);
	}

	@SuppressWarnings("unused")
	private String getRequestUrl(HttpServletRequest request) {
		return request.getRequestURI();
	}

	/**
	 * @Title: urlIsNeedValidate
	 * @Description: 判断url是否需要验证
	 * @param @param requestUrl
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private boolean urlIsNeedValidate(String requestUrl) {
		List<String> list = TxtFileCacheUtil.get(NO_LOGIN_URL_FILE);
		if (list != null) {
			for (String string : list) {
				Pattern pattern = Pattern.compile(string);
				Matcher matcher = pattern.matcher(requestUrl);
				boolean b = matcher.matches();
				if (b) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 获取登陆用户信息，兼容php
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private UserModel getUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserModel userModel = UserUtil.getUserModel(request, response,ClientChannelEnum.PIC);
		if (userModel == null) {
			userModel = this.getPhpUser(request, response);
			UserUtil.putSessionUserModel(request, response, userModel);
		}
		return userModel;
	}

	private UserModel getPhpUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			Cookie HXX_COOKIE = ServletUtil.getCookie(request, "HXX_COOKIE");
			if (HXX_COOKIE != null) {
				String value = HXX_COOKIE.getValue();
				logger.debug(value);
				if (StringUtil.isNotEmpty(value)) {
					String pref = "hxx:";
					value = URLDecoder.decode(value, "UTF-8");
					if (!value.startsWith(pref)) {
						return null;
					}
					value = value.substring(pref.length());
					logger.debug(value);
					JSONObject jo = JSON.parseObject(value);
					Long user_id = null;
					String password = null;
					String lastdate = null;
					String user_id_str = jo.getString("user_id");
					if (StringUtil.isNotEmpty(user_id_str)) {
						user_id = Long.valueOf(user_id_str);
					}
					String password_str = jo.getString("password");
					if (StringUtil.isNotEmpty(password_str)) {
						password = password_str;
					}
					String lastdate_str = jo.getString("lastdate");
					if (StringUtil.isNotEmpty(lastdate_str)) {
						lastdate = lastdate_str;
					}
					if (user_id != null && StringUtil.isNotEmpty(password)
							&& StringUtil.isNotEmpty(lastdate)) {
						UserSession userModel = this.userService
								.getUserSession(user_id);
						if (userModel != null) {
							if (DigestUtils.md5Hex(
									userModel.getUser_id()
											+ userModel.getPassword()
											+ userModel.getLastdate()).equals(
									password)) {
								String temp = userModel.getMobile() != null ? userModel
										.getMobile().toString() : null;
								String idCard = UserUtil
										.disposeIdCard(userModel.getIdcard());
								String mobile = UserUtil.disposeMobile(temp);

								userModel.setIdCardStr(idCard);
								userModel.setMobileStr(mobile);
								return userModel;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("解析php cookie出错" + e.getMessage());
		}
		return null;
	}

	@ServiceRemoteProxy
	private IUserService userService;
}
